<?php

class DeleteQueryBuilder implements SQLQueryBuilder {

    /**
     * @var Table
     */
    protected $table;

    /**
     * @var CriteriaCollection
     */
    protected $criterion;

    /**
     * @var string
     */
    protected $limit;

    /**
     * @param string $tableName
     */
    public function __construct($tableName) {
        $this->table = new Table($tableName);
        $this->criterion = new CriteriaCollection();
    }

    /**
     * @return string
     */
    private function getFromClause() {
        return 'FROM ' . $this->table->getName();
    }

    /**
     * @return string
     */
    private function getWhereClause() {
        if(is_null($this->criterion) || $this->criterion->getCriteriaCount() == 0) { return ''; }
        return ' WHERE ' . $this->criterion->getCriteriaString();
    }

    /**
     * @param Criteria $criteria
     */
    public function addCriteria($criteria) {
        $this->criterion->addCriteria($criteria);
    }

    /**
     * @param Criteria $criteria
     */
    public function addOrCriteria($criteria) {
        $this->criterion->addOrCriteria($criteria);
    }

    /**
     * @param int $numberOfRecordsToDelete
     */
    public function addLimit($numberOfRecordsToDelete) {
        $this->limit = $numberOfRecordsToDelete;
    }

    /**
     * @return string
     */
    private function getLimitClause() {
        return $this->limit ? ' LIMIT ' . $this->limit : '';
    }

    /**
     * @return string
     */
    private function getDeleteFromTableClause() {
        return 'DELETE '.$this->getFromClause();
    }

    /**
     * @return string
     */
    public function getSQLQuery() {
        $sqlString = $this->getDeleteFromTableClause();
        $sqlString .= $this->getWhereClause();
        $sqlString .= $this->getLimitClause();
        $sqlString .= ';';
        return $sqlString;
    }

}